package com.memory.modules.business.service.user.impl;

import com.memory.common.data.PageSort;
import com.memory.modules.business.domain.user.Account;
import com.memory.modules.business.repository.user.AccountRepository;
import com.memory.modules.business.service.user.AccountService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @PackageName: com.memory.modules.business.service.user.impl
 * @ClassName: AccountServiceImpl
 * @Description:
 * @author: zhuguangxun
 * @date 2021/3/10
 */
@Service
@RequiredArgsConstructor
public class AccountServiceImpl implements AccountService {

    private final AccountRepository accountRepository;

    @Override
    public Account create(Account account) {
        return accountRepository.save(account);
    }

    @Override
    public Account modify(Long id, Account account) {
        account.setId(id);
        findById(id).map(acc -> accountRepository.save(account));
        return null;
    }

    @Override
    public Account remove(Long id) {
        return findById(id)
                .map(e -> {
                    accountRepository.delete(e);
                    return e;
                }).orElse(null);
    }

    @Override
    public Optional<Account> findById(Long id) {
        return accountRepository.findById(id);
    }

    @Override
    public Account findByOpenId(String openId) {
        return accountRepository.findByOpenId(openId);
    }

    @Override
    public Page<Account> findPage(Example<Account> example) {
        final PageRequest pageRequest = PageSort.pageRequest();
        return accountRepository.findAll(example, pageRequest);
    }

    @Override
    public List<Account> findList(Example<Account> example) {
        return accountRepository.findAll(example);
    }


}
